package com.apexsoft.front.common.db.mysql;

import java.beans.PropertyVetoException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.apexsoft.front.common.config.CommonConfig;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 数据库连接池对象
 * @author dinglei
 *
 */
public final class MysqlDBPool {
	
	private static final Logger log = LogManager.getRootLogger();
	
	private static ComboPooledDataSource cpds = null;
	private static boolean isInit = false;
	
	public static void initDbConnectionPool(){
		try{
			cpds = new ComboPooledDataSource();
			cpds.setDriverClass(CommonConfig.getString("DB.MYSQL.DriverClass"));
			cpds.setJdbcUrl(CommonConfig.getString("DB.MYSQL.JdbcUrl"));
			cpds.setUser(CommonConfig.getString("DB.MYSQL.User"));
			cpds.setPassword(CommonConfig.getString("DB.MYSQL.Password"));
			cpds.setInitialPoolSize(CommonConfig.getInt("DB.MYSQL.InitialPoolSize"));
			cpds.setAcquireIncrement(CommonConfig.getInt("DB.MYSQL.AcquireIncrement"));
			cpds.setMinPoolSize(CommonConfig.getInt("DB.MYSQL.MinPoolSize"));
			cpds.setMaxPoolSize(CommonConfig.getInt("DB.MYSQL.MaxPoolSize"));
			cpds.setMaxIdleTime(CommonConfig.getInt("DB.MYSQL.MaxIdleTime"));
		}
		catch(PropertyVetoException e){
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}
	
	public static Map<String,String> getDbState(){
		Map<String,String> map = new HashMap<String,String>();
		try{
			map.put("numConnections", String.valueOf(cpds.getNumConnectionsAllUsers()));
			map.put("numBusyConnections", String.valueOf(cpds.getNumBusyConnectionsAllUsers()));
			map.put("numIdleConnections", String.valueOf(cpds.getNumIdleConnectionsAllUsers()));
			map.put("numUnclosedOrphanedConnections", String.valueOf(cpds.getNumUnclosedOrphanedConnectionsAllUsers()));
			map.put("numUserPools", String.valueOf(cpds.getNumUserPools()));
		}catch(SQLException e){
			e.printStackTrace();
		}
		return map;
	}
	
	public static ComboPooledDataSource getDataSource(){
		if(!isInit){
			MysqlDBPool.initDbConnectionPool();
			isInit = true;
		}
		return cpds;
	}
	
	public final void closePool(){
		cpds.close();
	}

}
